package zhishuang.wang.sansi.x9.tcpservice;

/**
 * @Author Zhishuang.Wang
 * @Date 2023/7/5 11:22
 * @Email 1406110602@qq.com
 */

import zhishuang.wang.sansi.fcms.protocol.ProtocolPackage;
import zhishuang.wang.sansi.tools.PrintRunLog;
import zhishuang.wang.sansi.tools.check.CrcCheck;
import zhishuang.wang.sansi.x9.devinfor.DeviceInforX9;
import zhishuang.wang.sansi.x9.devinfor.DeviceInforX9Var;
import zhishuang.wang.sansi.x9.plantask.PlanDown;
import zhishuang.wang.sansi.x9.protocol.X9ProtocolDeal;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class NettyX9Service extends ChannelInboundHandlerAdapter {
    private static Map<String, String> channleDeviceMap = new HashMap();
    private static Map<String, ChannelHandlerContext> deviceChannleMap = new HashMap();
    private static Map<String, byte[]> x9RemainData = new HashMap();

    public NettyX9Service() {
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf buf = (ByteBuf)msg;
            byte[] byteBuff = new byte[buf.readableBytes()];
            buf.readBytes(byteBuff);
            String channelId = ctx.channel().id().asShortText();
            byte[] remainBytes = (byte[])x9RemainData.get(channelId);
            if (remainBytes != null) {
                int remainBytesLength = remainBytes.length;
                int byteBuffLength = byteBuff.length;
                byte[] dataBuff = new byte[remainBytesLength + byteBuffLength];
                System.arraycopy(remainBytes, 0, dataBuff, 0, remainBytesLength);
                System.arraycopy(byteBuff, 0, dataBuff, remainBytesLength, byteBuffLength);
                x9RemainData.remove(channelId);
                PrintRunLog.printByteArrayInfor("netty byte:", dataBuff);
                this.x9ProtocolSubpackage(dataBuff, channelId, ctx);
            } else {
                PrintRunLog.printByteArrayInfor("netty byte:", byteBuff);
                this.x9ProtocolSubpackage(byteBuff, channelId, ctx);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        String channelId = ctx.channel().id().asShortText();
        String deviceId = (String)channleDeviceMap.get(channelId);
        x9RemainData.remove(channelId);
        if (deviceId != null && X9ProtocolDeal.x9RealStatusPush != null) {
            X9ProtocolDeal.x9RealStatusPush.deviceOnlineStatus(deviceId, 0);
            DeviceInforX9Var.devX9InforMapLock.lock();
            DeviceInforX9 dix9 = (DeviceInforX9)DeviceInforX9Var.devX9InforMap.get(deviceId);
            if (dix9 != null) {
                dix9.setOnlineFlag(0);
                DeviceInforX9Var.devX9InforMap.put(deviceId, dix9);
            }

            DeviceInforX9Var.devX9InforMapLock.unlock();
        }

    }

    public static int sendMessageToX9(byte[] data, String deviceId) {
        ChannelHandlerContext ctx = (ChannelHandlerContext)deviceChannleMap.get(deviceId);
        if (ctx != null) {
            if (ctx.isRemoved()) {
                return 2;
            } else {
                try {
                    PrintRunLog.printByteArrayInfor("send byte:", data);
                    ByteBuf echoBuf = Unpooled.buffer(data.length);
                    echoBuf.writeBytes(data);
                    ctx.writeAndFlush(echoBuf);
                    return 0;
                } catch (Exception var4) {
                    var4.printStackTrace();
                    return 3;
                }
            }
        } else {
            return 1;
        }
    }

    public void x9ProtocolSubpackage(byte[] data, String channelId, ChannelHandlerContext ctx) {
        int startP = 0;
        int dataLen = data.length;
        int i = 0;

        byte[] proBuff;
        while(i < dataLen) {
            if (data[i] != 2) {
                ++i;
            } else {
                int j;
                for(j = i + 1; j < dataLen; ++j) {
                    if (data[j] == 3) {
                        proBuff = Arrays.copyOfRange(data, i, j + 1);
                        this.x9ProtocolAnalysis(proBuff, channelId, ctx);
                        i = j + 1;
                        startP = i;
                    }
                }

                if (j >= dataLen) {
                    break;
                }
            }
        }

        if (startP < dataLen) {
            proBuff = Arrays.copyOfRange(data, startP, dataLen);
            if (proBuff.length < 512) {
                x9RemainData.put(channelId, proBuff);
            }
        }

    }

    public int x9ProtocolAnalysis(byte[] data, String channelId, ChannelHandlerContext ctx) {
        byte[] baseData = ProtocolPackage.revToBaseData(data);
        if (baseData != null && baseData.length > 14) {
            int baseDataLen = baseData.length;
            int crcStartP = baseDataLen - 2;
            int crcVal = baseData[baseDataLen - 2] & 255;
            int checkCrcVal = CrcCheck.sumCheckCal(baseData, 1, crcStartP);
            if (crcVal == checkCrcVal) {
                String deviceId = ProtocolPackage.getHexStr(baseData, 1, 8);
                DeviceInforX9Var.devX9InforMapLock.lock();
                DeviceInforX9 dix9 = (DeviceInforX9)DeviceInforX9Var.devX9InforMap.get(deviceId);
                if (dix9 != null) {
                    if (dix9.getOnlineFlag() == 0) {
                        dix9.setOnlineFlag(1);
                        DeviceInforX9Var.devX9InforMap.put(deviceId, dix9);

                        try {
                            X9ProtocolDeal.x9OnlinStatusPush(deviceId, 1);
                        } catch (Exception var15) {
                            var15.printStackTrace();
                        }
                    }

                    DeviceInforX9Var.devX9InforMapLock.unlock();
                    channleDeviceMap.put(channelId, deviceId);
                    deviceChannleMap.put(deviceId, ctx);

                    try {
                        int folNum = ProtocolPackage.getIntVal(baseData, 9, 2);
                        int cmd = baseData[12] & 127;
                        System.out.println("deviceId===" + deviceId + "===cmd:" + String.format("%02x", cmd));
                        switch (cmd) {
                            case 1:
                                X9ProtocolDeal.x9LoginInDeal(baseData, dix9.getPlayIds(), deviceId, folNum);
                                X9ProtocolDeal.x9AutoTimeToDevice(deviceId);
                                X9ProtocolDeal.x9BlockSizeSet(deviceId);
                                X9ProtocolDeal.x9AutoReadStatus(deviceId);
                                break;
                            case 2:
                                X9ProtocolDeal.x9BeatDeal(deviceId, folNum);
                            case 3:
                            case 4:
                            case 5:
                            case 7:
                            case 15:
                            case 17:
                            case 18:
                            case 22:
                            case 23:
                            case 25:
                            case 26:
                            case 33:
                            case 34:
                            case 36:
                            case 37:
                            case 39:
                            case 40:
                            case 43:
                            default:
                                break;
                            case 6:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 8);
                                break;
                            case 8:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 4);
                                X9ProtocolDeal.x9StatusQueryDeal(baseData, deviceId, 14, folNum, 0);
                                break;
                            case 9:
                                X9ProtocolDeal.x9StatusQueryDeal(baseData, deviceId, 13, folNum, 1);
                                break;
                            case 10:
                                X9ProtocolDeal.x9FaultStatusUploadDeal(baseData, deviceId, 13, folNum);
                                break;
                            case 11:
                                PlanDown.delPlanMapBytes(deviceId, baseData[13] & 255);
                                break;
                            case 12:
                                if (folNum == 65535) {
                                    X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 13);
                                } else {
                                    PlanDown.delPlanMapBytes(deviceId, baseData[13] & 255);
                                }
                                break;
                            case 13:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 2);
                                break;
                            case 14:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 1);
                                break;
                            case 16:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 12);
                                break;
                            case 19:
                            case 27:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 3);
                                break;
                            case 20:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 5);
                                break;
                            case 21:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 6);
                                X9ProtocolDeal.x9PlayStatusQueryDeal(baseData, deviceId, 14, folNum, 0);
                                break;
                            case 24:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 9);
                                break;
                            case 28:
                                X9ProtocolDeal.x9EnvironmentReqDeal(baseData, deviceId, 13, folNum);
                                break;
                            case 29:
                                X9ProtocolDeal.x9MaterialStatusUploadDeal(data, deviceId, 13, folNum);
                                break;
                            case 30:
                                X9ProtocolDeal.x9PlayStatusQueryDeal(baseData, deviceId, 13, folNum, 1);
                                break;
                            case 31:
                                X9ProtocolDeal.x9EnvironmentVarDeal(baseData, deviceId, 13, folNum, 1);
                                break;
                            case 32:
                            case 38:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 7);
                                X9ProtocolDeal.x9EnvironmentVarDeal(baseData, deviceId, 14, folNum, 0);
                                break;
                            case 35:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 10);
                                break;
                            case 41:
                                X9ProtocolDeal.x9SwitchDimControl(deviceId, folNum, baseData[13] & 255, 11);
                                break;
                            case 42:
                                X9ProtocolDeal.x9UpgradeStatusDeal(baseData, deviceId, 13, folNum);
                                break;
                            case 44:
                                X9ProtocolDeal.x9PlanExecStatusUploadDeal(baseData, deviceId, 13, folNum);
                        }
                    } catch (Exception var14) {
                        var14.printStackTrace();
                    }
                } else {
                    DeviceInforX9Var.devX9InforMapLock.unlock();

                    try {
                        ctx.close();
                    } catch (Exception var13) {
                        var13.printStackTrace();
                    }
                }
            }
        }

        return 0;
    }
}
